//
//  IMINetConnection.m
//  IMINet
//
//  Created by Travis on 09-11-13.
//  Copyright 2009 Exmart. All rights reserved.
//

#import "IMINetConnection.h"
#import "IMINetConnectionManager.h"


@implementation IMINetConnection
@synthesize uuid,request,response,manager;
@synthesize username,password;
@synthesize totalBytes=contentLength;

- (id) initWithRequest:(IMINetRequest *)req{
	[req generate];
	self = [super initWithRequest:req delegate:self];
	if (self != nil) {
		self.uuid=req.uuid;
		
		self.request=req;
		self.response=[IMINetResponse response];
	}
	return self;
}

- (id) initWithRequest:(IMINetRequest *)req delegate:(NSObject<IMINetConnectionDelegate> *)delegate
{
	
	self=[self initWithRequest:req];
	if (self != nil) {
		NSLog(@"%@ Connetct to:%@",self.uuid,[req.URL description]);
		target=delegate;
	}
	return self;
}
- (void)dealloc
{
    [self.response release];
    [super dealloc];
}

- (NSUInteger)loadedBytes{
	return [self.response.data length];
}
#pragma mark NSURLConnection delegate methods


- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
	if([challenge previousFailureCount] == 0 && ![challenge proposedCredential]){
		
		
		NSURLCredential *credential = [NSURLCredential credentialWithUser:username password:password 
															  persistence:NSURLCredentialPersistenceForSession];
		[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
		challenge=nil;
		
	}else {
		[[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
	}
	
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)res
{

    // This method is called when the server has determined that it has enough information to create the NSURLResponse.
    // it can be called multiple times, for example in the case of a redirect, so each time we reset the data.
    [self.response.data setLength:0];
    
    // Get response code.
    NSHTTPURLResponse *resp = (NSHTTPURLResponse *)res;
	
	
	
    NSInteger statusCode = [resp statusCode];
    
	if(statusCode>=200 && statusCode<300){
		self.response.MIMEType=[resp MIMEType];
		
		contentLength = [[[resp allHeaderFields] objectForKey:@"Content-Length"] intValue];
		[self dispatchEvent:[NSEvent eventWithKey:IMINetConnectionEventSuccess withObject:nil]];
		
		if([target respondsToSelector:@selector(connection:successWithContentLength:)])
			[target connection:self successWithContentLength:contentLength];
	}else if(statusCode>=400){
		[connection cancel];
		[self dispatchEvent:[NSEvent eventWithKey:IMINetConnectionEventFail withObject:[NSHTTPURLResponse localizedStringForStatusCode:statusCode]]];
		if([target respondsToSelector:@selector(connection:failWithString:)])
			[target connection:self failWithString:[NSHTTPURLResponse localizedStringForStatusCode:statusCode]];
	}else if(statusCode<400 && statusCode>=300){
		//redirct
		 
	}

	/*
    if (statusCode >= 400) {
        // Assume failure, and report to delegate.
        NSError *error = [NSError errorWithDomain:@"HTTP" code:statusCode userInfo:nil];
		if ([self _isValidDelegateForSelector:@selector(requestFailed:withError:)])
			[_delegate requestFailed:[connection identifier] withError:error];
        
        // Destroy the connection.
        [connection cancel];
		NSString *connectionIdentifier = [connection identifier];
		[_connections removeObjectForKey:connectionIdentifier];
		if ([self _isValidDelegateForSelector:@selector(connectionFinished:)])
			[_delegate connectionFinished:connectionIdentifier];
		
    } else if (statusCode == 304 || [connection responseType] == MGTwitterGeneric) {
        // Not modified, or generic success.
		if ([self _isValidDelegateForSelector:@selector(requestSucceeded:)])
			[_delegate requestSucceeded:[connection identifier]];
        if (statusCode == 304) {
            [self parsingSucceededForRequest:[connection identifier] 
                              ofResponseType:[connection responseType] 
                           withParsedObjects:[NSArray array]];
        }
        
        // Destroy the connection.
        [connection cancel];
		NSString *connectionIdentifier = [connection identifier];
		[_connections removeObjectForKey:connectionIdentifier];
		if ([self _isValidDelegateForSelector:@selector(connectionFinished:)])
			[_delegate connectionFinished:connectionIdentifier];
    }
    
#if DEBUG
    if (NO) {
        // Display headers for debugging.
        NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response;
        NSLog(@"MGTwitterEngine: (%d) [%@]:\r%@", 
              [resp statusCode], 
              [NSHTTPURLResponse localizedStringForStatusCode:[resp statusCode]], 
              [resp allHeaderFields]);
    }
#endif*/
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)dt
{
    // Append the new data to the receivedData.
    [self.response.data appendData:dt];
	if([target respondsToSelector:@selector(connectionDidReceiveData:)])
		[target connectionDidReceiveData:self];
}



- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	[manager removeConnection:self];
	
	if([target respondsToSelector:@selector(connectionDidFinishLoading:)])
		[target connectionDidFinishLoading:self];
	
}



@end
